package com.binarysoft.service.id;

import java.util.ArrayList;
import java.util.Collection;
import java.util.LinkedList;

import common.framework.dsb.AbstractServiceBean;
import common.framework.dsb.annotation.DSBService;
import common.framework.dsb.service.ServiceContext;

@DSBService(name = "DSB/IDService", startup = true)
public class IDServiceBean extends AbstractServiceBean implements IDService {
	private LinkedList<Long> cacheIDs = new LinkedList<Long>();
	private IDDAO idDAO = null;
	private int numberOfIDs = 1000;

	/*
	 * 
	 * @see
	 * common.framework.dsb.AbstractServiceBean#start(common.framework.dsb.server
	 * .ServiceContext)
	 */
	@Override
	public void start(ServiceContext serviceContext) throws Exception {
		super.start(serviceContext);
		idDAO = new IDMysqlDAO();
		loadData();
	}

	public void close() throws Exception {
	}

	public void refresh() throws Exception {
	}

	@Override
	public Collection<Long> getCacheIDs() throws Exception {
		return new ArrayList<Long>(cacheIDs);
	}

	/*
	 * 
	 * @see com.ideal.ems.service.id.IDService#nextID()
	 */
	public synchronized long nextID() throws Exception {
		// long currentID = System.nanoTime();
		// return currentID;
		Long rs = null;
		if (cacheIDs.size() <= 0) {
			loadData();
		}
		if (cacheIDs.size() > 0) {
			rs = cacheIDs.removeFirst();
		}
		if (rs != null) {
			return rs.longValue();
		} else {
			throw new Exception("ID resource limited.");
		}
	}

	private void loadData() throws Exception {
		Collection<Long> initIDs = idDAO.nextIDs(numberOfIDs);
		cacheIDs.clear();
		cacheIDs.addAll(initIDs);
	}

	public static void main(String[] args) {
	}// main
}
